package com.ershui.blog.system.controller;

import com.ershui.blog.system.domain.AjaxResult;
import com.ershui.blog.system.domain.SysLoginDto;
import com.ershui.blog.system.util.StringUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 登录验证
 * @author jinbin
 */
@Controller
public class SysLoginController {
    public static final Logger log = LoggerFactory.getLogger(com.ershui.blog.system.controller.SysLoginController.class);

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    //生成验证码
    @GetMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        byte[] captcha=null;
        ByteArrayOutputStream  out=new ByteArrayOutputStream();

        String createText=defaultKaptcha.createText();
        request.getSession().setAttribute("rightCode",createText);
        BufferedImage bi=defaultKaptcha.createImage(createText);
        try {
            ImageIO.write(bi,"jpg",out);
        } catch (IOException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captcha=out.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream sout = response.getOutputStream();
        sout.write(captcha);
        sout.flush();
        sout.close();
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
        return "login.html";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(SysLoginDto sysLoginDto,HttpServletRequest request){
        //验证码校验
        String rightCode = (String) request.getSession().getAttribute("rightCode");
        String code=sysLoginDto.getCaptcha();
//        if(!rightCode.equals(code)){
//            String msg="验证码不正确";
//            return AjaxResult.error(msg);
//        }
        //账号密码验证
        UsernamePasswordToken token=new UsernamePasswordToken(sysLoginDto.getUsername(),sysLoginDto.getPassword());
        Subject subject= SecurityUtils.getSubject();
        //设置是否记住我
        Boolean rememberme=sysLoginDto.getRememberMe()==null?false:sysLoginDto.getRememberMe();
        token.setRememberMe(rememberme);
        try {
            subject.login(token);
            if(rememberme){
                log.info("用户["+token.getUsername()+"]启用了自动登录");
            }
            return AjaxResult.sucess();
        }catch (UnknownAccountException e){
            String msg="用户或者密码不正确";
            if(StringUtils.isNotEmpty(e.getMessage())){
                msg=e.getMessage();
            }
            return AjaxResult.error(msg);
        }
    }
}
